<template>
  <div>
    <div class="form-box">
      <div class="form-item">
        <div class="title">昵称</div>
        <input
          type="text"
          placeholder="请输入昵称"
          v-model="formData.nickName"
        />
      </div>
    </div>
    <div class="save-btn" @click="toSave">保存</div>
  </div>
</template>
<script setup lang="ts">
import { updateUser } from "@/api/user";
import { useUser } from "@/store";
import { Result, ResultError, UserType } from "@/types";
import { ref, getCurrentInstance, onMounted } from "vue";

import { storeToRefs } from 'pinia';

const { user } = storeToRefs(useUser())

const {
  proxy,
  proxy: { $utils },
} = getCurrentInstance() as any;

const formData = ref<{
  nickName: string;
}>({
  nickName: "",
});

const toSave = () => {
  var data = {
    nickName: formData.value.nickName,
  };
  var rule = [
    { name: "nickName", checkType: "required", errorMsg: "请输入昵称" },
  ];
  var checkRes = $utils.check(data, rule);
  if (!checkRes) {
    $utils.errorMsg({ title: $utils.error });
    return;
  }
  updateUser(data)
    .then((res: Result) => {
      useUser().setUser(res.data)
      $utils.successMsg("保存成功");
      setTimeout( () => {
        uni.navigateBack();
      }, 1500);
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

onMounted(() => {
  if ($utils.checkLogin("login")) {
    user.value = useUser().getUser;
    formData.value.nickName = user.value?.nickName || "";
  }
});
</script>

<style scoped>
.form-box {
  width: calc(100% - 40rpx);
  margin: 0 auto;
  display: flex;
  align-items: center;
}
.form-item {
  width: 100%;
  display: flex;
  height: 100rpx;
  line-height: 100rpx;
  align-items: center;
  border-bottom: 1rpx solid #f0f0f0;
  justify-content: space-between;
}
.form-item .title {
  width: 120rpx;
}
.form-item input {
  width: calc(100% - 140rpx);
}
.save-btn {
  width: calc(100% - 40rpx);
  margin: 50rpx auto;
  background: #f0f0f0;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: var(--base-radius-default);
  text-align: center;
}
</style>